#pragma strict
////////////////////////
///高度图工具
////////////////////////

class HeightMapTool{
	/**
		根据高度图生成,顶点uv切线.
	*/
	static function GenerateVertexUVTangent(heightMap:Texture2D,size:Vector3):Object{
		var width:int = Mathf.Min(heightMap.width,255);
		var height:int = Mathf.Min(heightMap.height,255);
		
		var vertices:Vector3[] = new Vector3[height * width];
		var uv:Vector2[] = new Vector2[height * width];
		var tangents:Vector4[] = new Vector4[height * width];
		
		var uvScale:Vector2 = Vector2(1.0/(width-1),1.0/(height-1));
		var sizeScale:Vector3 = Vector3(size.x/(width-1),size.y,size.x/(height-1));
		
		for(var y:int=0;y<height;y++){
			for(var x:int=0;x<width;x++){
				var pixelHeight = heightMap.GetPixel(x,y).grayscale;
				var vertex:Vector3 = Vector3(x,pixelHeight,y);
				var index:int = y * width + x;
				
				vertices[index] = Vector3.Scale(vertex,sizeScale);
				uv[index] = Vector2.Scale(Vector2(x,y),uvScale);
				//tangent
				var vertexL:Vector3 = Vector3(x-1,heightMap.GetPixel(x-1,y).grayscale,y);
				var vertexR:Vector3 = Vector3(x+1,heightMap.GetPixel(x+1,y).grayscale,y);
				var tan:Vector3 = Vector3.Scale(vertexR - vertexL,sizeScale);
				tangents[index] = Vector4(tan.x,tan.y,tan.z,-1.0);
			}
		}
		return {"vertices":vertices,"uv":uv,"tangents":tangents};
	}
	/**
		根据高度图,生成三角对索引.
	*/
	static function GenerateTriangles(texture:Texture2D):int[]{
		var width:int = texture.width;
		var height:int = texture.height;
		////矩形顶点数组,建立三角对数组.
		var triangles:int[] = new int[(height-1)*(width-1)*6];//每个矩形,有6个点,2个三角形.
		var index:int = 0;
		for(var y:int = 0;y<height-1;y++){
			for(var x:int = 0;x<width-1;x++){
				//3   (y+1) * width + x, (y+1) * width + x + 1
				//1    y * width + x, y * width + x + 1
				var leftTop:int = (y + 1) * width + x;
				var rightTop:int = leftTop + 1;
				var leftBottom:int = y * width + x;
				var rightBottom:int = leftBottom + 1;
				
				triangles[index++] = leftBottom;
				triangles[index++] = leftTop;
				triangles[index++] = rightBottom;
				
				triangles[index++] = leftTop;
				triangles[index++] = rightTop;
				triangles[index++] = rightBottom;
			}
		}
		return triangles;
	}
	
}